import 'package:BeeApp/CarPage/CarRealNameModelPage.dart';
import 'package:BeeApp/MainPage/MainModelPage.dart';
import 'package:BeeApp/MainPage/MainToolPage.dart';
import 'package:BeeApp/MainPage/http_request.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

class CarRealNamePage extends StatefulWidget {
  CarRealNamePage({Key key}) : super(key: key);

  @override
  _CarNewsRealPageState createState() => _CarNewsRealPageState();
}

class _CarNewsRealPageState extends State<CarRealNamePage> {
  RealNameModel realNameModel;
  final carText = TextEditingController();
  final nameText = TextEditingController();
  final codeText = TextEditingController();
  final mobileText = TextEditingController();
  final otherText = TextEditingController();
  final otherMobileText = TextEditingController();
  List<Asset> images = List<Asset>();
  List<Asset> images01 = List<Asset>();
  List<Asset> images02 = List<Asset>();
  List<Asset> images03 = List<Asset>();
  List<Asset> images04 = List<Asset>();
  List<Asset> images05 = List<Asset>();
  List<Asset> images06 = List<Asset>();
  List<Asset> images07 = List<Asset>();
  String imageStr01 = "";
  String imageStr02 = "";
  String imageStr03 = "";
  String imageStr04 = "";
  String imageStr05 = "";
  String imageStr06 = "";
  String imageStr07 = "";
  String realStr = "";
  String realType = "提交审核";
  int chooseType;
  bool ischange = true;
  @override
  void initState() {
    super.initState();
    uploadRealName();
  }

  void uploadRealName() {
    DioUtils.postHttp(
      context,
      "Usercommon/realname_info",
      parameters: {"token": getData("token")},
      onSuccess: (t) {
        print(t);
        MainModel model = MainModel.fromJson(t);
        if (model.code == 1 && model.data != null) {
          if (mounted) {
            setState(() {
              ischange = false;
              realNameModel = RealNameModel.fromJson(t);
              realStr = realNameModel.data.remark != null
                  ? realNameModel.data.remark
                  : "";
              if (realNameModel.data.auditStatus == 1) {
                realType = "审核中";
              } else {
                realType = "修改审核";
              }
              carText.text = realNameModel.data.carNumber;
              nameText.text = realNameModel.data.realname;
              codeText.text = realNameModel.data.idcard;
              mobileText.text = realNameModel.data.mobile;
              otherText.text = realNameModel.data.pressLinkMan;
              otherMobileText.text = realNameModel.data.linkManMobile;
              imageStr01 = realNameModel.data.idcardFrontImage;
              imageStr02 = realNameModel.data.idcardBackImage;
              imageStr03 = realNameModel.data.driversLicenseImage1;
              imageStr04 = realNameModel.data.driversLicenseImage2;
              imageStr05 = realNameModel.data.drivingLicenseImage1;
              imageStr06 = realNameModel.data.drivingLicenseImage2;
              imageStr07 = realNameModel.data.carImage;
            });
          }
        }
      },
      onError: (error) {
        print(error);
      },
    );
  }

  Widget lineView() {
    return Container(
      height: 1,
      width: 900,
      color: Colors.grey[300],
    );
  }

  Text labelText(String str) {
    return Text(
      str,
      style: TextStyle(
        color: Color(0xFF333333),
        fontSize: setFontSize(32),
        fontWeight: FontWeight.bold,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFFF5F5F5),
      appBar: getAppBar(context, "车主认证"),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: ListView(
          children: <Widget>[
            SizedBox(height: 8),
            realStr.length > 0
                ? Container(
                    color: Colors.white,
                    padding: EdgeInsets.only(top: 10, left: 10, right: 10),
                    child: Column(
                      children: [
                        Row(
                          children: [
                            labelText("审核结果:"),
                            SizedBox(width: 10),
                            Expanded(child: labelText(realStr)),
                          ],
                        ),
                        SizedBox(height: 10),
                        lineView()
                      ],
                    ),
                  )
                : Container(),
            Container(
              color: Colors.white,
              padding: EdgeInsets.all(setWidth(30)),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  labelText("请拍摄并上传身份证"),
                  SizedBox(height: 8),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      chooseCodeView(
                          "images/RealCodeImage01.png", "点击上传带头像一面", 1),
                      chooseCodeView(
                          "images/RealCodeImage02.png", "点击上传带国徽一面", 2),
                    ],
                  ),
                ],
              ),
            ),
            SizedBox(height: 8),
            Container(
              color: Colors.white,
              padding: EdgeInsets.only(
                left: setWidth(30),
                right: setWidth(30),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  textView("车牌号:", "请输入车牌号", carText),
                  lineView(),
                  textView("姓    名:", "请输入姓名", nameText),
                  lineView(),
                  textView("身份证:", "请输入身份证", codeText),
                  lineView(),
                  textView(
                    "联系电话:",
                    "请输入联系电话",
                    mobileText,
                    keyType: TextInputType.number,
                  ),
                  lineView(),
                  // textView("紧急联系人:", "请输入联系人姓名", otherText),
                  // lineView(),
                  // textView(
                  //   "紧急联系电话:",
                  //   "请输入联系人电话",
                  //   otherMobileText,
                  //   keyType: TextInputType.number,
                  // ),
                  lineView(),
                  SizedBox(height: setHeight(60)),
                  labelText("请拍摄并上传驾驶证"),
                  SizedBox(height: setHeight(20)),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      chooseView("images/RealCarImage01.png", 3),
                      chooseView("images/RealCarImage03.png", 4),
                    ],
                  ),
                  SizedBox(height: setHeight(60)),
                  labelText("请拍摄并上传行驶证"),
                  SizedBox(height: setHeight(20)),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      chooseView("images/RealCarImage02.png", 5),
                      chooseView("images/RealCarImage03.png", 6),
                    ],
                  ),
                  SizedBox(height: setHeight(60)),
                  labelText("请上传车辆照片"),
                  SizedBox(height: setHeight(20)),
                  chooseEndView(),
                  SizedBox(height: 20),
                  btnView(),
                  SizedBox(height: 20),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget chooseCodeView(String imageStr, String title, int index) {
    return Column(
      children: <Widget>[
        chooseView(imageStr, index),
        SizedBox(height: 8),
        Text(
          title,
          style: TextStyle(
            color: Color(0xFF666666),
            fontSize: setFontSize(28),
            fontWeight: FontWeight.bold,
          ),
        ),
      ],
    );
  }

  Widget chooseView(String imageStr, int index) {
    return InkWell(
      child: Container(
        alignment: Alignment.center,
        height: setHeight(210),
        width: (screenWidth - setWidth(80)) / 2,
        decoration: BoxDecoration(
          color: Colors.yellow,
          borderRadius: BorderRadius.all(Radius.circular(10.0)),
          border: Border.all(
              color: index == 1 || index == 2 ? Colors.grey : Colors.white,
              width: 1),
          image: DecorationImage(
            image: AssetImage(imageStr),
            fit: BoxFit.cover,
          ),
        ),
        child: showimage(index),
      ),
      onTap: () async {
        print("object$index");
        if (!ischange) {
          return;
        }
        chooseType = index;
        if (await Permission.camera.request().isGranted &&
            await Permission.photos.request().isGranted) {
          loadAssets();
          print('权限申请通过');
        } else {
          showToast('请前往设置，打开相机权限');
        }
      },
    );
  }

  // 获取相册图片
  Future<void> loadAssets() async {
    List<Asset> resultList = List<Asset>();
    String error = 'No Error Dectected';
    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 1,
        enableCamera: true,
        selectedAssets: images,
        materialOptions: MaterialOptions(
          startInAllView: true,
          allViewTitle: "所有照片",
          actionBarColor: "#abcdef",
          textOnNothingSelected: "请选择图片",
          selectionLimitReachedText: "最多选择1张图片",
        ),
      );
    } on Exception catch (e) {
      error = e.toString();
      print("aaaaa" + error);
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
    if (resultList.length == 0) {
      return;
    }

    DioUtils.postImageHttp(
      context,
      "common/uploads",
      images: resultList,
      onSuccess: (t) {
        print(t);
        Map dic = Map.from(t);
        if (dic["code"] == 1) {
          setState(() {
            switch (chooseType) {
              case 1:
                {
                  images01 = resultList;
                  imageStr01 = dic["data"]["url"][0];
                }
                break;
              case 2:
                {
                  images02 = resultList;
                  imageStr02 = dic["data"]["url"][0];
                }
                break;
              case 3:
                {
                  images03 = resultList;
                  imageStr03 = dic["data"]["url"][0];
                }
                break;
              case 4:
                {
                  images04 = resultList;
                  imageStr04 = dic["data"]["url"][0];
                }
                break;
              case 5:
                {
                  images05 = resultList;
                  imageStr05 = dic["data"]["url"][0];
                }
                break;
              case 6:
                {
                  images06 = resultList;
                  imageStr06 = dic["data"]["url"][0];
                }
                break;
              case 7:
                {
                  images07 = resultList;
                  imageStr07 = dic["data"]["url"][0];
                }
                break;
              default:
            }
          });
        }
      },
      onError: (error) {},
    );
  }

  Widget showimage(int index) {
    if (index == 1) {
      return showimageNews(index, images01);
    } else if (index == 2) {
      return showimageNews(index, images02);
    } else if (index == 3) {
      return showimageNews(index, images03);
    } else if (index == 4) {
      return showimageNews(index, images04);
    } else if (index == 5) {
      return showimageNews(index, images05);
    } else if (index == 6) {
      return showimageNews(index, images06);
    } else if (index == 7) {
      return showimageNews(index, images07);
    } else {
      return Image.asset(
        "images/RealAddImage.png",
        width: setHeight(100),
        height: setHeight(100),
      );
    }
  }

  Widget showimageNews(int index, List<Asset> images) {
    if (images.length == 0 && realNameModel == null) {
      return Image.asset(
        "images/RealAddImage.png",
        width: setHeight(100),
        height: setHeight(100),
      );
    } else {
      if (images.length > 0) {
        Asset asset = images[0];
        return AssetThumb(
          asset: asset,
          width: 300,
          height: 300,
        );
      } else {
        if (index == 1) {
          return CachedNetworkImage(
              imageUrl: realNameModel.data.idcardFrontImage);
        } else if (index == 2) {
          return CachedNetworkImage(
              imageUrl: realNameModel.data.idcardBackImage);
        } else if (index == 3) {
          return CachedNetworkImage(
              imageUrl: realNameModel.data.driversLicenseImage1);
        } else if (index == 4) {
          return CachedNetworkImage(
              imageUrl: realNameModel.data.driversLicenseImage2);
        } else if (index == 5) {
          return CachedNetworkImage(
              imageUrl: realNameModel.data.drivingLicenseImage1);
        } else if (index == 6) {
          return CachedNetworkImage(
              imageUrl: realNameModel.data.drivingLicenseImage2);
        } else {
          return CachedNetworkImage(imageUrl: realNameModel.data.carImage);
        }
      }
    }
  }

  Widget textView(
    String string,
    String hintStr,
    TextEditingController controller, {
    TextInputType keyType = TextInputType.text,
  }) {
    return Container(
      color: Colors.white,
      child: Row(
        children: [
          labelText(string),
          SizedBox(width: 10),
          Expanded(
              child: TextField(
            readOnly: !ischange,
            controller: controller,
            textAlign: TextAlign.start,
            keyboardType: keyType,
            cursorColor: Colors.grey[400], //设置光标
            decoration: InputDecoration(
                border: InputBorder.none,
                hintText: hintStr,
                hintStyle: TextStyle(
                    fontSize: setFontSize(30), color: Color(0xFFAEAEAE))),
            style: TextStyle(
              fontSize: setFontSize(30),
              color: Color(0xFF333333),
              fontWeight: FontWeight.bold,
            ),
          )),
        ],
      ),
    );
  }

  Widget chooseEndView() {
    return InkWell(
      child: Container(
        height: setHeight(180),
        width: setHeight(180),
        color: Color(0xFFF5F5F5),
        alignment: Alignment.center,
        child: showimage(7),
      ),
      onTap: () async {
        print("object001");
        if (!ischange) {
          return;
        }
        chooseType = 7;
        if (await Permission.camera.request().isGranted &&
            await Permission.photos.request().isGranted) {
          loadAssets();
          print('权限申请通过');
        } else {
          showToast('请前往设置，打开相机权限');
        }
      },
    );
  }

  Widget btnView() {
    return Container(
      alignment: Alignment.center,
      child: InkWell(
        child: Container(
          width: setWidth(300),
          alignment: Alignment.center,
          padding: EdgeInsets.all(setHeight(20)),
          decoration: BoxDecoration(
            color: Color(0xFFFF8629),
            borderRadius: BorderRadius.all(Radius.circular(10)),
            border: Border.all(color: Colors.black, width: 2), //边框
          ),
          child: Text(
            realType,
            style: TextStyle(
              color: Color(0xFF222222),
              fontSize: setFontSize(34),
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        onTap: () {
          if (realNameModel.data.auditStatus == 1) {
            showToast("审核中，请等待");
            return;
          }
          if (ischange) {
            upLoadNews();
          } else {
            setState(() {
              ischange = true;
            });
          }
          // upLoadNews();
        },
      ),
    );
  }

  void upLoadNews() {
    removeFocus(context);
    if (imageStr01.length == 0) {
      showToast("请上传身份证带头像一面图片");
      return;
    }
    if (imageStr02.length == 0) {
      showToast("请上传身份证带国徽一面图片");
      return;
    }
    if (carText.text.length == 0) {
      showToast("请输入车牌号");
      return;
    }
    if (nameText.text.length == 0) {
      showToast("请输入姓名");
      return;
    }
    if (codeText.text.length == 0) {
      showToast("请输入身份证");
      return;
    }
    if (!RegexUtil.isMobileSimple(mobileText.text)) {
      showToast("请输入手机号");
      return;
    }
    // if (otherText.text.length == 0) {
    //   showToast("请输入紧急联系人");
    //   return;
    // }
    // if (!RegexUtil.isMobileSimple(otherMobileText.text)) {
    //   showToast("请输入紧急联系电话");
    //   return;
    // }
    if (imageStr03.length == 0 || imageStr04.length == 0) {
      showToast("请上传驾驶证");
      return;
    }
    if (imageStr05.length == 0 || imageStr06.length == 0) {
      showToast("请上传行驶证");
      return;
    }
    if (imageStr07.length == 0) {
      showToast("请上传近期人车合影照");
      return;
    }
    Map<String, dynamic> dic = Map();
    if (realNameModel != null) {
      dic["id"] = realNameModel.data.id.toString();
    }
    dic["token"] = getData("token");
    dic["car_number"] = carText.text;
    dic["realname"] = nameText.text;
    dic["idcard"] = codeText.text;
    dic["mobile"] = mobileText.text;
    // dic["press_link_man"] = otherText.text;
    // dic["link_man_mobile"] = otherMobileText.text;
    dic["idcard_front_image"] = imageStr01;
    dic["idcard_back_image"] = imageStr02;
    dic["drivers_license_image1"] = imageStr03;
    dic["drivers_license_image2"] = imageStr04;
    dic["driving_license_image1"] = imageStr05;
    dic["driving_license_image2"] = imageStr06;
    dic["car_image"] = imageStr07;
    showLoading(context);
    DioUtils.postHttp(
      context,
      "Usercenter/caruser_realname",
      parameters: dic,
      onSuccess: (t) {
        print(t);
        dismissLoading(context);
        // showToast(t["msg"]);
        showAlertDialog(context, t["msg"]);
      },
      onError: (error) {
        dismissLoading(context);
        print(error);
      },
    );
  }

  showAlertDialog(BuildContext context, String title) {
    //显示对话框
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(title),
          // content: Text("确定要退出吗?"),
          // 设置成 圆角
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          actions: [
            FlatButton(
              child: Text(
                "确认",
                style: TextStyle(
                  color: Colors.orange,
                  fontSize: setFontSize(30),
                ),
              ),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
          ],
        );
      },
    );
  }
}
